import { InjectRedis } from '@nestjs-modules/ioredis';
import { Global, Injectable, Module } from '@nestjs/common';
import Redis from 'ioredis';

@Injectable()
export class RedisClient {
  @InjectRedis() private readonly redis: Redis;

  set(key: string, value: string, time?: number) {
    time ? this.redis.set(key, value, 'EX', time) : this.redis.set(key, value);
  }

  del(key: string) {
    this.redis.del(key);
  }

  async get(key: string) {
    const value = await this.redis.get(key);
    return value ? value.toString() : null;
  }

  async exists(key: string) {
    const result = await this.redis.exists(key);
    return result;
  }
}

@Global()
@Module({
  providers: [RedisClient],
  exports: [RedisClient],
})
export class IoRedisModule {}
